package com.yinhai.redis.cluster.serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.shaded.org.objenesis.strategy.StdInstantiatorStrategy;

/**
 * 基于Kryo实现的序列化器
 * @author dreamlee
 *
 */
public class KryoSerializer implements ISerializable {
	
	private Kryo kryo;
	
	private Output output=new Output(new byte[1024]);
	private Input input=new Input(new byte[1024]);
	
	public KryoSerializer(){
		kryo = new Kryo();  
		kryo.setReferences(false);  
		kryo.setRegistrationRequired(false);  
		kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());  
	}

	@Override
	public Object deSerialize(byte[] data) {
		if(data==null) return null;
		input.setInputStream(new ByteArrayInputStream(data));
		return kryo.readClassAndObject(input);
	}

	@Override
	public byte[] serialize(Object obj) {
		if(obj==null) return null;
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		output.setOutputStream(bos);
		kryo.writeClassAndObject(output, obj);
		output.flush();
		return bos.toByteArray();
	}

}
